home *** CD-ROM | disk | FTP | other *** search
- Path: news.gate.net!pslfl2-37
- From: bhutto@gate.net (William Hutto)
- Newsgroups: comp.lang.c
- Subject: Re: quick decision: is n a power of 2?
- Date: 20 Jan 1996 20:34:20 GMT
- Organization: CyberGate, Inc.
- Message-ID: <4drjkc$il4@news.gate.net>
- References: <Pine.OSF.3.91.960119114608.18779E-100000@io.UWinnipeg.ca> <4dpian$gij@oxy.rust.net>
- NNTP-Posting-Host: pslfl2-37.gate.net
- X-Newsreader: News Xpress Version 1.0 Beta #4
-
- In article <4dpian$gij@oxy.rust.net>, ebennett@rust.net spake:
- ;Bill Simpson <wsimpson@uwinnipeg.ca> wrote:
- ;
- ;>Is there a fast way to decide whether a number n is a power of 2?
- ;
- ;
- ;Working with positive numbers, a number will be a power of 2 if there
- ;is exactly one bit set in the number. (For negative numbers, you can
- ;use the following by taking the abs() of the number).
-
- Negative numbers? The person in question wasn't asking for a power of -2.
- Power of 2 has to be > 0 for integers.
-
- ;
- ;Given some number, there is a neat trick to generate a mask which will
- ;have exactly one bit set in it. The bit set will be the least
- ;significant non-zero bit in the original number:
- ;
- ; mask = ~number & number;
-
- It's faster just to use:
-
- mask = 0;
-
- ;
- ;Now, if number contained a single non-zero bit (and is therefore a
- ;power of 2), mask will be equal to number. Therefore:
- ;
- ; if (number == (~number & number))
-
- if(!number)
-
- ; {
- ; /* number is a power of 2 */
-
- /* number == 0 */
-
- ; }
- ;
-
- Bill
-
- "Whatcha got on?...Your mind?"
-